package cn.gzjp.modules.it.api.web;

import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.config.Global;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.it.api.bean.CommonJson;
import cn.gzjp.modules.it.api.bean.PhotoResizeVo;
import cn.gzjp.modules.it.api.bean.XinszVo;
import cn.gzjp.modules.it.entity.Car;
import cn.gzjp.modules.it.entity.Member;
import cn.gzjp.modules.it.service.CarService;
import cn.gzjp.modules.it.service.MemberService;
import com.baidu.aip.face.AipFace;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baidu.aip.ocr.AipOcr;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传管理
 */
@Controller("frontUpload")
@Api(value = "文件上传管理", description = "文件上传管理")
@RequestMapping("${frontPath}/upload")
public class UploadController extends BaseController {

    public static final String APP_ID = "10576505";
    public static final String API_KEY = "EIeg8vTBY5RDof8hPynA55A5";
    public static final String SECRET_KEY = "9IbrpntjheaBjyRFw5dw5LkZOdxWDWmT";
    @Autowired
    private CarService carService;
    @Autowired
    private MemberService memberService;


    Map<String, Integer> openidXingszMap = new HashMap<String, Integer>();
    Map<String, Integer> openidChepaiMap = new HashMap<String, Integer>();

    /**
     * 行驶证识别
     * @param file
     * @param openid
     * @param p 第几张 默认1
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "行驶证上传")
    @RequestMapping(value = "xingsz", method = RequestMethod.POST)
    @ApiImplicitParams ({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
            @ApiImplicitParam(name="p",value="第几张图",dataType="int",paramType="form",required =true)
    })
    @ResponseBody
    public String xingsz(MultipartFile file, String openid,int p, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("行驶证开始上传 openid=" + openid+"|p="+p);
        CommonJson result = new CommonJson();
        result.setData(0);
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/xingsz/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        //log.info("行驶证开始上传到=" + path);
        if (StringUtils.isBlank(openid)) {
            result.setCode(1);
            result.setMsg("openid参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if(p==0){
            result.setCode(1);
            result.setMsg("p参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;

        }
        log.info("行驶证图片上传成功地址=" + destPath);

//        Integer count = openidXingszMap.get(openid);
//        log.info(openid + " 上传的行驶证图片张数" + count);
//        if (count == null) {
//            count = 0;
//        }
//        if (count < 3) {
//            count++;
//            openidXingszMap.put(openid, count);
//           // log.info("数量不够无数据返回");
//           // return null;
//        }

//        log.info(openid + " 上传的行驶证图片张数" + count + " 开始识别...");
//        count = 0;
//        openidXingszMap.put(openid, count);
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject res = client.vehicleLicense(destPath, options);
        log.info("识别出行驶证信息=" + res.toString());

        String error_msg;
        try {
            error_msg = res.getString("error_msg");
            if (StringUtils.isNotBlank(error_msg)) {
                result.setCode(2);
                result.setMsg("行驶证无法识别,请重新扫描");
                return mapper.toJson(result);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String hphm;
        XinszVo license;
        try {
            JSONObject words_result = res.getJSONObject("words_result");
            JSONObject clsbdhJson = words_result.getJSONObject("车辆识别代号");
            String clsbdh = clsbdhJson.getString("words");
            JSONObject zzJson = words_result.getJSONObject("住址");
            String zz = zzJson.getString("words");
            JSONObject ppxhJson = words_result.getJSONObject("品牌型号");
            String ppxh = ppxhJson.getString("words");
            JSONObject fzrqJson = words_result.getJSONObject("发证日期");
            String fzrq = fzrqJson.getString("words");

            JSONObject cllxJson = words_result.getJSONObject("车辆类型");
            String cllx = cllxJson.getString("words");

            JSONObject syrJson = words_result.getJSONObject("所有人");
            String syr = syrJson.getString("words");

            JSONObject syxzJson = words_result.getJSONObject("使用性质");
            String syxz = syxzJson.getString("words");
            JSONObject fdjhmJson = words_result.getJSONObject("发动机号码");
            String fdjhm = fdjhmJson.getString("words");

            JSONObject hphmJson = words_result.getJSONObject("号牌号码");
            hphm = hphmJson.getString("words");
            JSONObject zcrqJson = words_result.getJSONObject("注册日期");
            String zcrq = zcrqJson.getString("words");

            license = new XinszVo();
            license.setClsbdh(clsbdh);
            license.setZz(zz);
            license.setFzrq(fzrq);
            license.setPpxh(ppxh);
            license.setCllx(cllx);
            license.setSyr(syr);
            license.setSyxz(syxz);
            license.setFdjhm(fdjhm);
            license.setHphm(hphm);
            license.setZcrq(zcrq);

            log.info("发动机号码=" + license.getFdjhm());
            log.info("车辆识别代号=" + license.getClsbdh());
            log.info("车牌=" + hphm);
            if (StringUtils.isNotBlank(hphm) && hphm.length() >= 7 && StringUtils.isNotBlank(license.getFdjhm())
                    && license.getFdjhm().length() >= 5 && StringUtils.isNotBlank(license.getClsbdh())
                    && license.getClsbdh().length() >= 5) {
                result.setData(license);
            } else {
                result.setCode(2);
                result.setData(0);
                if (p>=3){
                    result.setData(2);
                }
                if (p>=9){
                    result.setData(3);
                }
                result.setMsg("行驶证无法识别，请重新扫描");
            }
        } catch (Exception e) {
            result.setCode(2);
            result.setData(0);
            if (p>=3){
                result.setData(2);
            }
            if (p>=9){
                result.setData(3);
            }
            result.setMsg("行驶证无法识别，请重新扫描");
        }
        log.info("返回数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }

    /**
     * 车牌识别
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "车牌上传")
    @RequestMapping(value = "chepai", method = RequestMethod.POST)
    @ApiImplicitParams ({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
            @ApiImplicitParam(name="p",value="第几张图",dataType="int",paramType="form",required =true)
    })
    @ResponseBody
    public String chepai(MultipartFile file, String openid,int p, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("车牌开始上传 openid=" + openid+"|p="+p);
        CommonJson result = new CommonJson();
        result.setData(0);
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/chepai/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        //log.info("车牌开始上传到=" + path);
        if (StringUtils.isBlank(openid)) {
            result.setCode(1);
            result.setMsg("openid参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if(p==0){
            result.setCode(1);
            result.setMsg("p参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;

        }
        log.info("车牌上传成功图片地址=" + destPath);

//        Integer count = openidChepaiMap.get(openid);
//        log.info(openid + " 上传的车牌图片张数" + count);
//        if (count == null) {
//            count = 0;
//        }
//        if (count < 3) {
//            count++;
//            openidChepaiMap.put(openid, count);
//            log.info("数量不够无数据返回");
//            return null;
//        }
//        log.info(openid + " 上传的行车牌图片张数" + count + " 开始识别...");
//        count = 0;
//        openidChepaiMap.put(openid, count);

        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject res = client.plateLicense(destPath, options);
        log.info("识别出车牌信息=" + res.toString());

        String error_msg;
        try {
            error_msg = res.getString("error_msg");
            if (StringUtils.isNotBlank(error_msg)) {
                result.setCode(2);
                result.setData(0);
                if (p>=3){
                    result.setData(2);
                }
                if (p>=9){
                    result.setData(3);
                }
                result.setMsg("车牌无法识别,请重新扫描");
                log.info("返回数据:" + this.mapper.toJson(result));
                return mapper.toJson(result);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//			result.setCode(2);
//			result.setMsg("车牌无法识别");
//			log.info("返回数据:" + JsonUtils.toJson(result));
//			return JsonUtils.toJson(result);
        }
        try {
            JSONObject words_result = res.getJSONObject("words_result");
            String number = words_result.getString("number");
            String color = words_result.getString("color");
            result.setData(number);
            log.info("车牌=" + number);
            log.info("颜色=" + color);
            log.info("返回数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        } catch (Exception e) {
            result.setCode(2);
            result.setData(0);
            if (p>=3){
                result.setData(2);
            }
            if (p>=9){
                result.setData(3);
            }
            result.setMsg("车牌无法识别,请重新扫描");
            log.info("返回数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }

    }

    /**
     * 驾驶证上传
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "驾驶证上传")
    @RequestMapping(value = "jiasz", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "chepai", value = "车牌", dataType = "String", paramType = "form", required = true),
            @ApiImplicitParam(name = "type", value = "正本 type为1 副本type为2", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String jiasz(MultipartFile file, String chepai, String type, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CommonJson result = new CommonJson();
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/jiasz/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        log.info("驾驶证开始上传到=" + path);
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            return mapper.toJson(result);
        }
        if (StringUtils.isBlank(chepai)) {
            result.setCode(1);
            result.setMsg("chepai参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (StringUtils.isBlank(type)) {
            result.setCode(1);
            result.setMsg("type参数不能为空,正本 type为1 副本type为2");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        Car car = carService.get(chepai);
        if (car == null) {
            result.setCode(-1);
            result.setMsg("车牌对应的车辆不存在");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        String accessPath = "";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;
            accessPath = Global.getConfig("photoUrl") + "/userfiles/jiasz/" + fileName + "." + extension;
        }
        if ("1".equals(type)) {
            car.setJszImg1(accessPath);
        } else {
            car.setJszImg2(accessPath);
        }
        carService.save(car);
        result.setData(accessPath);
        log.info("驾驶证上传返回数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);

    }


    /**
     * 挪车照片上传
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "挪车照片上传")
    @RequestMapping(value = "moveCarImg", method = RequestMethod.POST)
    @ResponseBody
    public String moveCarImg(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CommonJson result = new CommonJson();
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/moveCar/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        log.info("挪车照片开始上传到=" + path);
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            return mapper.toJson(result);
        }

        String accessPath = "";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;
            accessPath = Global.getConfig("photoUrl") + "/userfiles/moveCar/" + fileName + "." + extension;
        }

        result.setData(accessPath);
        log.info("挪车照片上传:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);

    }

    /**
     * 头像上传
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "会员头像")
    @RequestMapping(value = "headImg", method = RequestMethod.POST)
    @ResponseBody
    public String headImg(MultipartFile file, String openid, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CommonJson result = new CommonJson();
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/headImg/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        log.info("会员头像开始上传到=" + path);
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            return mapper.toJson(result);
        }
        if (StringUtils.isBlank(openid)) {
            result.setCode(1);
            result.setMsg("openid参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if ("undefined".equals(openid)) {
            result.setMsg("openid有误，请核对");
            result.setCode(1);
            log.info(mapper.toJson(result));
            return this.mapper.toJson(result);
        }


        String accessPath = "";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;
            accessPath = Global.getConfig("photoUrl") + "/userfiles/headImg/" + fileName + "." + extension;
        }
        Member member = memberService.get(openid);
        if (member != null) {
            member.setHeadImg(accessPath);
            memberService.save(member);
        }
        result.setData(accessPath);
        log.info("会员头像上传:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);

    }


    /**
     * 相片压缩参数获取
     * @return
     */
    @ApiOperation(value = "相片压缩参数获取")
    @RequestMapping(value = "getPiexlNumAndQuality", method = RequestMethod.GET)
    @ResponseBody
    public String getPiexlNumAndQuality() {
        log.info("相片压缩参数获取");
        CommonJson result = new CommonJson();
        PhotoResizeVo vo = new PhotoResizeVo();
        String  piexlNum = ConfigUtils.getProperty("piexlNum");
        String quality = ConfigUtils.getProperty("quality");
        vo.setPiexlNum(piexlNum);
        vo.setQuality(quality);
        result.setData(vo);
        log.info("相片压缩参数获取返回给小程序数据:"+this.mapper.toJson(result));
        return this.mapper.toJson(result);
    }



    /**
     * 身份证上传
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "身份证上传")
    @RequestMapping(value = "idcard", method = RequestMethod.POST)
    @ApiImplicitParams ({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
            @ApiImplicitParam(name = "type", value = "正面 type为1 反面type为2", dataType = "String", paramType = "form", required = true)
    })
    @ResponseBody
    public String idcard(MultipartFile file, String openid,String type, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("身份证上传开始上传 openid=" + openid+"|type="+type);
        CommonJson result = new CommonJson();
        result.setData(0);
        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/idcard/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        if (StringUtils.isBlank(openid)) {
            result.setCode(1);
            result.setMsg("openid参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if(StringUtils.isNotBlank(type)){
            result.setCode(1);
            result.setMsg("type参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
       String accessPath="";
        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;
            accessPath = Global.getConfig("photoUrl") + "/userfiles/idcard/" + fileName + "." + extension;
            result.setData(accessPath);

        }
        log.info("身份证上传成功图片地址=" + destPath);

        if("1".equals(type)){//上传的是身份证正面
            AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            JSONObject res = client.plateLicense(destPath, options);
            log.info("识别出身份证信息=" + res.toString());

            String error_msg;
            try {
                error_msg = res.getString("error_msg");
                if (StringUtils.isNotBlank(error_msg)) {
                    result.setCode(2);
                    result.setData(0);

                    result.setMsg("身份证无法识别,请重新上传");
                    log.info("返回数据:" + this.mapper.toJson(result));
                    return mapper.toJson(result);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            try {
                String imageStatus = res.getString("image_status");
                log.info("imageStatus="+imageStatus);
                if(!"normal".equals(imageStatus)){
                    result.setCode(2);
                    result.setData(0);
                    result.setMsg("身份证无法识别,请重新上传");
                }else{
                    Member member = memberService.get(openid);
                    if (member != null) {
                        member.setIdcardImg1(destPath);
                        memberService.save(member);
                    }
                }
                log.info("返回数据:" + this.mapper.toJson(result));
                return this.mapper.toJson(result);
            } catch (Exception e) {
                result.setCode(2);
                result.setData(0);

                result.setMsg("身份证无法识别,请重新上传");
                log.info("返回数据:" + this.mapper.toJson(result));
                return this.mapper.toJson(result);
            }

        }else {
            Member member = memberService.get(openid);
            if (member != null) {
                member.setIdcardImg2(destPath);
                memberService.save(member);
            }
        }
        log.info("返回数据:" + this.mapper.toJson(result));
        return this.mapper.toJson(result);

    }

    /**
     * 人脸认证
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "人脸认证")
    @RequestMapping(value = "faceMatch", method = RequestMethod.POST)
    @ApiImplicitParams ({
            @ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true)
    })
    @ResponseBody
    public String faceMatch(MultipartFile file, String openid,  HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("人脸开始上传 openid=" + openid);
        CommonJson result = new CommonJson();

        Member member = memberService.get(openid);
        if(member==null||StringUtils.isBlank(member.getIdcardImg1())){
            result.setCode(1);
            result.setMsg("请先上传身份证信息");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }

        // 获取文件需要上传到的路径
        String path = Global.getFileUploadPath() + "/userfiles/face/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String destPath = path + fileName;
        if (StringUtils.isBlank(openid)) {
            result.setCode(1);
            result.setMsg("openid参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }
        if (file == null) {
            result.setCode(1);
            result.setMsg("file参数不能为空");
            log.info("返回数据:" + this.mapper.toJson(result));
            return mapper.toJson(result);
        }

        if (!file.isEmpty()) {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            File outPutFile = new File(destPath + "." + extension);
            FileUtils.writeByteArrayToFile(outPutFile, file.getBytes());
            destPath = destPath + "." + extension;

        }
        log.info("人脸上传成功图片地址=" + destPath);



        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);





        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("ext_fields", "qualities");
        options.put("image_liveness", ",faceliveness");
        options.put("types", "7,13");

        //参数为本地图片路径列表
        String path1 = destPath;
        String path2 = member.getIdcardImg1();


        ArrayList<String> images = new ArrayList<String>();
        images.add(path1);
        images.add(path2);
        JSONObject res = client.match(images, options);
        System.out.println(res.toString(2));

        log.info("图片对比返回信息=" + res.toString());

        String error_msg;
        try {
            error_msg = res.getString("error_msg");
            if (StringUtils.isNotBlank(error_msg)) {
                result.setCode(2);
                result.setData(0);

                result.setMsg("对比失败,请重新上传");
                log.info("返回数据:" + this.mapper.toJson(result));
                return mapper.toJson(result);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//			result.setCode(2);
//			result.setMsg("车牌无法识别");
//			log.info("返回数据:" + JsonUtils.toJson(result));
//			return JsonUtils.toJson(result);
        }
        try {
            JSONObject words_result = res.getJSONObject("result");
            String score = words_result.getString("score");
            double s = Double.parseDouble(score);
            result.setData(score);
            if(s>=80){
                result.setCode(0);
                result.setMsg("认证成功");
                member = memberService.get(openid);
                if (member != null) {
                    member.setAuthstatus(1);
                    memberService.save(member);
                }
            }else{
                result.setCode(2);
                result.setMsg("无法匹配,请重新上传");
            }
            log.info("score=" + score);
            log.info("返回数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        } catch (Exception e) {
            result.setCode(2);
            result.setData(0);
            result.setMsg("无法匹配,请重新上传");
            log.info("返回数据:" + this.mapper.toJson(result));
            return this.mapper.toJson(result);
        }

    }
}